package master;

/**
 * @author chenyw
 * @date 2022/9/4 11:21
 */
public class M235lowestCommonAncestor {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        return dfs(root, p, q);
    }

    private TreeNode dfs(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }
        if (root.val == p.val || root.val == q.val) {
            return root;
        } else if (root.val > q.val && root.val > p.val) {
            return dfs(root.left, p, q);
        } else if (root.val < p.val && root.val < q.val) {
            return dfs(root.right, p, q);
        }
        return root;
    }
}
